import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';

export async function PUT(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户是否为企业负责人
    if (!user.is_company_admin) {
      return NextResponse.json(
        { error: '您不是企业负责人，无法更新企业资料' },
        { status: 403 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const {
      name,
      industry,
      size,
      location,
      website,
      description,
      logo
    } = body;

    // 验证必填字段
    if (!name) {
      return NextResponse.json(
        { error: '企业名称不能为空' },
        { status: 400 }
      );
    }

    // 获取企业ID
    const [companies] = await UserModel.query<any[]>(
      `SELECT id FROM companies WHERE admin_user_id = ? OR name = ? LIMIT 1`,
      [userId, user.company]
    );

    if (!companies || companies.length === 0) {
      return NextResponse.json(
        { error: '未找到企业信息' },
        { status: 404 }
      );
    }

    const companyId = companies[0].id;

    // 更新企业信息
    try {
      await UserModel.query(
        `UPDATE companies 
         SET name = ?, 
             industry = ?, 
             size = ?, 
             location = ?, 
             website = ?, 
             description = ?, 
             logo = ?,
             updated_at = NOW()
         WHERE id = ?`,
        [
          name,
          industry || null,
          size || null,
          location || null,
          website || null,
          description || null,
          logo || null,
          companyId
        ]
      );

      // 如果企业名称有变化，同时更新用户表中的公司名称
      if (name !== user.company) {
        await UserModel.updateProfile(userId, { company: name });
      }

      // 获取更新后的企业信息
      const [updatedCompany] = await UserModel.query<any[]>(
        `SELECT * FROM companies WHERE id = ?`,
        [companyId]
      );

      return NextResponse.json({
        message: '企业资料更新成功',
        company: updatedCompany[0]
      });
    } catch (dbError) {
      console.error('更新企业资料失败:', dbError);
      return NextResponse.json(
        { error: '更新企业资料失败' },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('更新企业资料错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
